﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace SO_DataFetcher.PubFunctions.DataBaseHelp
{
    public class MySqlHelp:DataBaseHelper
    {
        private static MySqlHelp _instance;

        public override void Instance()
        {
            _instance = new MySqlHelp();
        }
        private static MySqlConnection _mySqlConnection;
        private MySqlConnection MySqlConnection
        {
            get { return _mySqlConnection ?? (_mySqlConnection = new MySqlConnection(_instance.Connecting)); }
        }

        public override void GetConnectString(string ip, string port, string name, string psw, string dataTable)
        {
            _instance.Connecting = string.Format("Server={0},{1};User ID={2};Password={3};Trusted_Connection=False", ip, port, name, psw);
        }

        public override void ExecuteSql(string sql)
        {
            MySqlCommand cmd = new MySqlCommand(sql, _instance.MySqlConnection);
            try
            {
                OpenConnection();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                CloseConnection();
            }
        }

        public override DataSet GetDataSet(string sql)
        {
            DataSet ds = new DataSet();
            try
            {
                OpenConnection();

                MySqlDataAdapter adapter = new MySqlDataAdapter(sql, _instance.MySqlConnection);
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                CloseConnection();
            }

            return ds;
        }

        public override void OpenConnection()
        {
            if (_instance.MySqlConnection.State == ConnectionState.Closed)
                _instance.MySqlConnection.Open();
        }

        public override void CloseConnection()
        {
            if (_instance.MySqlConnection.State == ConnectionState.Open)
                _instance.MySqlConnection.Close();
        }
    }
}
